package com.freesky.common.utils.file;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

public class FileDownloadUtils {

    /**
     * 下载本地文件
     *
     * @param path
     * @param response
     * @throws FileNotFoundException
     */
    public static void downloadLocal(String path, String fileName, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        path = path.replace("%20", " ");
        // 文件名称
        if(null==fileName || "".equals(fileName)) {
            fileName = path.split("/")[path.split("/").length - 1];
        }
        // 读到流中
        InputStream inStream = new FileInputStream(path); // 文件的存放路径

        // 清空response
        response.reset();
        response.setContentType("application/octet-stream");
        try {
            //浏览器类型判断
            String BrowsersType = request.getHeader("User-Agent");
            //谷歌和火狐的判断
            if (!BrowsersType.contains("Chrome") && !BrowsersType.contains("Firefox")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {//其他类型的
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename="+ fileName);
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }

        } catch (IOException e) {
            String msg = e.toString();
            if(msg.indexOf("ClientAbortException")!=-1){
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
